package com.zhy.deploy.executor.defaultImpl;

import cn.hutool.core.util.StrUtil;
import com.zhy.deploy.config.BuildMetadata;
import com.zhy.deploy.config.TomcatConfig;
import com.zhy.deploy.executor.AbstractExecutor;
import com.zhy.deploy.websocket.SocketMessage;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * 拷贝war包到tomcat
 */
public class DefaultCopyExecutor extends AbstractExecutor {

    private SocketMessage socketMessage;

    public DefaultCopyExecutor(BuildMetadata metadata) {
        super(metadata);
        socketMessage = metadata.getMessage();
    }

    public void execute() throws IOException {

        TomcatConfig tomcatConfig = metadata.getTomcatConfig();

        //发布地址（tomcat webapps 目录）
        String webappPath = tomcatConfig.getWebappPath();
        socketMessage.info("Archiving "+webappPath);

        String workspace = metadata.getWorkspace();

        String projectName = metadata.getProjectName();

        String subProjectName = metadata.getSubProjectName();

        StringBuffer sb = new StringBuffer();

        sb.append(workspace).append(File.separator).append(projectName);
        if (StrUtil.isNotEmpty(subProjectName)) {
            sb.append(File.separator).append(subProjectName);
        }

        sb.append(File.separator).append("target");

        File warDir = new File(sb.toString());

        File[] files = warDir.listFiles((File file) -> {
            if (file.isFile()) {
                String name = file.getName();
                if (name.endsWith(".war")) {
                    return true;
                }
            }
            return false;
        });

        String backPath = tomcatConfig.getBackPath();
        backPath = StrUtil.isEmpty(backPath) ? workspace + File.separator + "back" : backPath;

        backups(files, webappPath, backPath);

        for (File war : files) {
            File backFile = new File(webappPath, war.getName());
            FileUtils.moveFile(war, backFile);
            socketMessage.info("Archiving "+war.getPath()+" To "+backFile.getPath() );
        }

    }

    /**
     * webapps 目录下的war文件备份
     *
     * @param localFiles
     * @param webappsDir
     * @param backDir
     * @throws IOException
     */
    public void backups(File[] localFiles, String webappsDir, String backDir) throws IOException {
        File warDir = new File(webappsDir);
        File[] wars = warDir.listFiles((File file) -> {
            if (file.isFile()) {
                String name = file.getName();
                if (name.endsWith(".war")) {
                    for (File localFile : localFiles) {
                        String localFileName = localFile.getName();
                        if (name.equals(localFileName)) {
                            return true;
                        }
                    }
                }
            }
            return false;
        });

        if (Objects.nonNull(wars) && wars.length > 0) {
            File backDirectory = new File(backDir);
            if (!backDirectory.isDirectory()) {
                backDirectory.mkdirs();
            }

            for (File war : wars) {
                long millis = System.currentTimeMillis();
                String backFileName = war.getName() + millis + ".back";
                File backFile = new File(backDirectory, backFileName);
                FileUtils.moveFile(war, backFile);

                socketMessage.info("Backups "+war.getPath()+" To "+backFile.getPath() );
            }
        }

    }
}
